<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="main-container">
            <div class="top-title">编辑广告</div>
            <div class="form-box" v-loading='loading'>
                <el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="100px" class="form" label-position='right'>
                    <span class="title">广告名称与备注</span>
                    <el-row :gutter="41" class="item-adv">
                        <el-col :span="10">
                            <el-form-item label="广告类型" prop="advId" :rules="rules.advId">
                                <el-select v-model="dataForm.advId" :disabled='true' placeholder="请选择" style="width:100%">
                                    <el-option v-for="item in advList" :key="item.value" :label="item.label" :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="广告名称" prop="advertName" :rules="rules.advertName">
                                <el-popover
                                placement="top-start"
                                trigger="focus" 
                                content="长度在20个字符以内。">
                                    <el-input v-model="dataForm.advertName" slot="reference" :maxlength="20"></el-input>
                                </el-popover> 
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41" class="item-adv" v-if="dataForm.advId == '2'">
                        <el-col :span="10">
                            <el-form-item label="指定位置" prop="advertAppType" :rules="rules.advertAppType">
                                <el-select v-model="dataForm.advertAppType" placeholder="请选择" style="width:100%">
                                    <el-option value="0" label="教学app"></el-option>
                                    <el-option value="1" label="家庭app"></el-option>
                                    <el-option value="2" label="教学和家庭app"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item label="设置显示时间（秒）" label-width="150px" prop="showTime" :rules="rules.showTime">
                                <el-input-number v-model="dataForm.showTime" :min="3" style="width:100%"></el-input-number>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41" class="item-adv">
                        <el-col :span="10">
                            <el-form-item label="备注" prop="remark" :rules="rules.remark">
                                <el-popover
                                placement="top-start"
                                trigger="focus" 
                                content="长度在20个字符以内。">
                                    <el-input v-model="dataForm.remark" slot="reference" :maxlength="20"></el-input>
                                </el-popover> 
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <span class="title title-pic">广告图片 <i>(支持 JPG PNG GIF 格式，200K以内的图片！)</i></span>
                    <el-row :gutter="41" class="item item-pic" v-if="dataForm.advId != '2'">
                        <el-col :span="10">
                            <div class="describe"><font color='red'>* </font><span v-if="dataForm.advId == '0'">广告图片(750 * 220)</span><span v-if="dataForm.advId == '3'">广告图片(690 * 200)</span></div>
                            <el-form-item label="" label-width="0">
                                <imgUpload  @onSuccess="btnAdvImg"  @remove="removeAdvImg" :file-list-show='true' :file-list.sync='imgPicList' :imgSize='0.1953125'>
                                    <div class="el-upload-new el-upload-picture-new">
                                        <div class="up-container el-upload">
                                            <i class="el-icon-plus"></i>
                                        </div>
                                    </div>
                                </imgUpload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41" class="item item-pic" v-if="dataForm.advId == '2'">
                        <el-col :span="10">
                            <div class="describe"><font color='red'>* </font>ios大图片(1242 * 2208)</div>
                            <el-form-item label="" label-width="0">
                                <imgUpload  @onSuccess="btnIosBigImg"  @remove="removeIosBigImg" :file-list-show='true' :file-list.sync='iosPicOneList' :imgSize='0.1953125' prop="iosPicOneList" :rules="rules.iosPicOneList">
                                    <div class="el-upload-new el-upload-picture-new">
                                        <div class="up-container el-upload">
                                            <i class="el-icon-plus"></i>
                                        </div>
                                    </div>
                                </imgUpload>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <div class="describe"><font color='red'>* </font>Android(720 * 1280)</div>
                            <el-form-item label="" label-width="0">
                                <imgUpload  @onSuccess="btnAndroidImg" @remove="removeAndroidImg" :file-list-show='true' :file-list.sync='androidPicList' :imgSize='0.1953125' prop="androidPic" :rules="rules.androidPic">
                                    <div class="el-upload-new el-upload-picture-new">
                                        <div class="up-container el-upload">
                                            <i class="el-icon-plus"></i>
                                        </div>
                                    </div>
                                </imgUpload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41" class="item item-pic" v-if="dataForm.advId == '2'">
                        <el-col :span="10">
                            <div class="describe">ios适中图片(640 * 1136)</div>
                            <el-form-item label="" label-width="0">
                                <imgUpload  @onSuccess="btnIosModerateImg" @remove="removeIosModerateImg" :file-list-show='true' :imgSize='0.1953125' :file-list.sync='iosPicTWOList'>
                                    <div class="el-upload-new el-upload-picture-new">
                                        <div class="up-container el-upload">
                                            <i class="el-icon-plus"></i>
                                        </div>
                                    </div>
                                </imgUpload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41" class="item item-pic" v-if="dataForm.advId == '2'">
                        <el-col :span="10">
                            <div class="describe">ios小图片(640 * 960)</div>
                            <el-form-item label="" label-width="0">
                                <imgUpload  @onSuccess="btnIosSmallImg"  @remove="removeIosSmallImg" :file-list-show='true' :imgSize='0.1953125' :file-list.sync='iosPicThreeList'>
                                    <div class="el-upload-new el-upload-picture-new">
                                        <div class="up-container el-upload">
                                            <i class="el-icon-plus"></i>
                                        </div>
                                    </div>
                                </imgUpload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <span class="title title-pic">广告链接与自定义内容</span>
                    <el-row :gutter="41" class="item">
                        <el-col :span="21">
                            <el-radio-group v-model="dataForm.advertOrCustom">
                                <el-radio class="radio" label="0">广告链接</el-radio>
                                <el-radio class="radio" label="1">自定义内容</el-radio>
                            </el-radio-group>
                            <div class="box">
                                <div v-if="dataForm.advertOrCustom === '0'">
                                    <el-form-item label="" label-width="0" prop="linkUrl" :rules="rules.linkUrl">
                                        <el-popover placement="top-start" trigger="focus" content="请输入http://或https://前缀链接">
                                            <el-input slot="reference" v-model="dataForm.linkUrl" placeholder="请输入链接" style="width:46%"></el-input>
                                        </el-popover>
                                    </el-form-item>
                                </div>
                                <div v-if="dataForm.advertOrCustom === '1'">
                                    <Tinymce :height="360" :id="tinymceId" v-model="dataForm.htmlSourceCode"></Tinymce>
                                </div>
                            </div>
                        </el-col>
                    </el-row>
                    <span class="title title-pic">投放区域</span>
                    <el-row :gutter="41" class="item">
                    <el-col :span="10">
                        <el-form-item label="省份" prop="provinceId" :rules="rules.provinceId">
                            <province v-model="dataForm.provinceId" @change="provinceChange"></province>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41" class="item">
                    <el-col :span="10" v-if="agentTypeState=='2' || agentTypeState=='3'">
                        <el-form-item label="城市" prop="cityId" :rules="rules.cityId">
                            <city v-model="dataForm.cityId" :province="dataForm.provinceId" ></city>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="41" class="item">
                    <el-col :span="10" v-if="agentTypeState=='3'">
                        <el-form-item label="区县" prop="areaId" :rules="rules.areaId">
                            <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                        </el-form-item>
                    </el-col>
                </el-row>
                <template  v-if="agentTypeState=='1'">
                    <el-row :gutter="41" class="item">
                        <el-col :span="10">
                            <el-form-item label="城市">
                                <city v-model="dataForm.cityId" :province="dataForm.provinceId" ></city>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="41" class="item">
                        <el-col :span="10">
                            <el-form-item label="区县">
                                <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
                <template  v-if="agentTypeState=='2'">
                    <el-row :gutter="41" class="item">
                        <el-col :span="10">
                            <el-form-item label="区县">
                                <region v-model="dataForm.areaId" :city="dataForm.cityId"></region>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </template>
                    <div class="man-bom"></div>
                    <el-row :gutter="41" type="flex" justify="center">
                        <el-col :span="2"><el-button @click="resetForm('dataForm')">取消</el-button></el-col>
                        <el-col :span="2"><el-button type="primary" @click="submitForm('dataForm')">保存</el-button></el-col>
                    </el-row>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
import { isEmpty } from 'utils/validate';
import Levelbar from '../../../layout/Levelbar';
import imgUpload from 'components/Upload/fileUpload';
import Tinymce from 'components/Tinymce';
import province from 'components/AdvArea/province';
import city from 'components/AdvArea/city';
import region from 'components/AdvArea/region';
import { getAdvertInfo, updateAdvert, listOrgRegionMapInfo } from 'api/advMangement';
import { mapGetters } from 'vuex';
export default {
    name: 'editAdv',
    components: { Levelbar, imgUpload, Tinymce, province, city, region},
    data() {
        const validateEmpty = (rule, value, callback) => {
            if (!isEmpty(value) && value) {
                callback(new Error('内容中不能存在空格'));
            } else {
                callback();
            }
        };
        return {
            tinymceId: 'tinymceId',
            userTypeList: [],
            agentTypeState: '1',
            advList: [
                {
                    label: '积分商城顶部广告位',
                    value: '0'
                },
                // {
                //     label: 'e学云教育平台首页广告位',
                //     value: '1'
                // },
                {
                    label: 'APP全屏广告位',
                    value: '2'
                },
                {
                    label: '周边教育广告',
                    value: '3'
                }
                // {
                //     label: '课程学习广告',
                //     value: '4'
                // }
            ],
            imgPicList: [],
            iosPicOneList: [],
            iosPicTWOList: [],
            iosPicThreeList: [],
            androidPicList: [],
            loading: false,
            dataForm: {
                advId: '0',
                advertName: '',
                remark: '',
                advertAppType: '0',
                showTime: 3,
                imgPic: '',
                iosPicOne: '',
                iosPicTWO: '',
                iosPicThree: '',
                androidPic: '',
                advertOrCustom: '0',
                linkUrl: '',
                htmlSourceCode: '',
                provinceId: '',
                cityId: '',
                areaId: ''
            },
            rules: {
                advId: [
                     { required: true, message: '内容不能为空', trigger: 'blur' }
                ],
                advertName: [
                    { required: true, message: '内容不能为空', trigger: 'blur' },
                    { required: true, trigger: 'blur', validator: validateEmpty },
                    { min: 1, max: 20, message: '长度在20个字符以内', trigger: 'blur' }
                ],
                remark: [
                    { validator: validateEmpty },
                    { min: 1, max: 20, message: '长度在20个字符以内', trigger: 'blur' }
                ],
                advertAppType: [
                    { required: true, message: '内容不能为空', trigger: 'blur' }
                ],
                showTime: [
                    { required: true, message: '内容不能为空'},
                    { pattern: /^\d{1}$/, message: '请输入不低于3的1位正整数'}  
                     // { pattern: /^\d/, message: '请输入不低于3的正整数'}
                ],
                linkUrl: [
                    { pattern: /^(https?):\/\/\w*\.\w*/, message: '请输入合法的url' }
                ],
                provinceId: [
                    { required: true, message: '请选择省份', trigger: 'blur' }
                ],
                cityId: [
                    { required: true, message: '请选择城市', trigger: 'blur' }
                ],
                areaId: [
                    { required: true, message: '请选择区县', trigger: 'blur' }
                ]
            }
        };
    },
    computed: {
        ...mapGetters([
            'agentType'
        ])
    },
    created() {
        this.getAgentType();
        this.getAdvertInfoFu();
    },
    methods: {
        getAgentType() {   
            listOrgRegionMapInfo().then(response => { 
                this.userTypeList = response.data.content;
            })
        },
        provinceChange(val) {
            let count = 0;
            this.userTypeList.some(item => {
                if (item.fProvinceId == val) {
                    if (count == 0) {
                        this.agentTypeState = item.fAgentType; 
                    } else {
                        if (item.fAgentType == '1') {
                            this.agentTypeState = '1';
                        } else if (item.fAgentType == '2' && this.agentTypeState != '1') {
                            this.agentTypeState = '2';
                        } else if (item.fAgentType == '3' && this.agentTypeState != '1' && this.agentTypeState != '2') {
                            this.agentTypeState = '3';
                        }
                    }
                    count = count + 1;
                }
            });
            
        },
        getAdvertInfoFu() {
                
            let pId = this.$route.params.id;
            this.loading = true;
            getAdvertInfo(pId).then(res => {
                this.loading = false;
                if (res.data.status == 200) {

                    this.dataForm.advId = res.data.content.sType;
                    this.dataForm.advertName = res.data.content.sName;
                    this.dataForm.remark = res.data.content.sDesc;
                    this.dataForm.advertAppType = res.data.content.sAppType;
                    this.dataForm.showTime = res.data.content.sShowTime;
                    this.dataForm.imgPic = res.data.content.sPic;
                    this.dataForm.iosPicOne = res.data.content.sIosOne;
                    this.dataForm.iosPicTWO = res.data.content.sIosTwo;
                    this.dataForm.iosPicThree = res.data.content.sIosThree;
                    this.dataForm.androidPic = res.data.content.sAndroid;
                    
                    if (res.data.content.sPic) {
                        this.imgPicList.push({name: res.data.content.sName, url: res.data.content.sPic});
                    }
                    if (res.data.content.sIosOne) {
                        this.iosPicOneList.push({name: res.data.content.sName, url: res.data.content.sIosOne});
                    }
                    if (res.data.content.sIosTwo) {
                        this.iosPicTWOList.push({name: res.data.content.sName, url: res.data.content.sIosTwo});
                    }
                    if (res.data.content.sIosThree) {
                        this.iosPicThreeList.push({name: res.data.content.sName, url: res.data.content.sIosThree});
                    }
                    if (res.data.content.sAndroid) {
                        this.androidPicList.push({name: res.data.content.sName, url: res.data.content.sAndroid});
                    }
                    
                    this.dataForm.advertOrCustom = res.data.content.sShowType;
                    this.dataForm.linkUrl = res.data.content.sLink;
                    this.dataForm.htmlSourceCode = res.data.content.sHtml;
                    this.dataForm.provinceId = res.data.content.fProvinceId;
                    this.dataForm.cityId = res.data.content.fCityId;
                    this.dataForm.areaId = res.data.content.fAreaId;

                } else {
                    this.$message.error(res.data.errorMsg);
                }
                
            })
        },
        btnAdvImg(obj) {
            this.imgPicList = obj;
            if (this.dataForm.advId == '0') {
                this.dataForm.imgPic = `${obj.imgUrl}?imageView2/2/w/750/h/220`;
            } else {
                this.dataForm.imgPic = `${obj.imgUrl}?imageView2/2/w/690/h/200`;
            }
        },
        removeAdvImg() {
            this.dataForm.imgPic = '';
        },
        btnIosBigImg(obj) {
            this.iosPicOneList = obj;
            // iOS：1242_2208    640_1136  640_960      Android:720_1280
            this.dataForm.iosPicOne = `${obj.imgUrl}?imageView2/2/w/1242/h/2208`;
        },
        removeIosBigImg() {
            this.dataForm.iosPicOne = '';
        },
        btnIosModerateImg(obj) {
            this.iosPicTWOList = obj;
            this.dataForm.iosPicTWO = `${obj.imgUrl}?imageView2/2/w/640/h/1136`;
        },
        removeIosModerateImg() {
            this.dataForm.iosPicTWO = '';
        },
        btnIosSmallImg(obj) {
            this.iosPicThreeList = obj;
            this.dataForm.iosPicThree = `${obj.imgUrl}?imageView2/2/w/640/h/960`; 
        },
        removeIosSmallImg() {
            this.dataForm.iosPicThree = '';
        },
        btnAndroidImg(obj) {
            this.androidPicList = obj;
            this.dataForm.androidPic = `${obj.imgUrl}?imageView2/2/w/720/h/1280`;       
        },
        removeAndroidImg() {
            this.dataForm.androidPic = '';
        },
        resetForm(dataForm) {
            this.$router.go(-1);
        },
        submitForm(dataForm) {
            this.$refs[dataForm].validate(valid => {
                if (valid) {

                    if (this.dataForm.advId == '2') {
                        if (!this.dataForm.iosPicOne) {
                            this.$message('请上传ios图片（1242*2208）');
                            return;
                        }

                        if (!this.dataForm.androidPic) {
                            this.$message('请上传android图片（720*1280）');
                            return;
                        }
                    } else {
                        if (!this.dataForm.imgPic) {
                            this.$message('请上传图片');
                            return;
                        }
                    }

                    if (this.dataForm.advertOrCustom === '1' && window.tinymce.get('tinymceId').getContent({format: 'text'}).trim().length > 6000) {
                        this.$message.error('自定义内容字数过多');
                        return false;
                    }

                    this.$confirm('是否保存?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: ' '
                    }).then(() => {
                        let pId = this.$route.params.id;
                        let advertName = this.dataForm.advertName; // 广告名称
                        let advertType = this.dataForm.advId; // 广告类型
                        let remark = this.dataForm.remark; // 备注
                        let advertAppType = this.dataForm.advertAppType; // 指定位置
                        let showTime = this.dataForm.showTime; // 设置显示时间
                        let iosPicOne = this.dataForm.iosPicOne; // ios图片 1242*2208
                        let iosPicTWO = this.dataForm.iosPicTWO; // ios图片 640*1136
                        let iosPicThree = this.dataForm.iosPicThree; // ios图片 640*960
                        let androidPic = this.dataForm.androidPic; // android图片 720*1280
                        let advertOrCustom = this.dataForm.advertOrCustom; // 广告展现形式 0:广告链接 1：自定义
                        let linkUrl = this.dataForm.linkUrl; // 如果是广告链接则填上链接地址
                        let htmlSourceCode = this.dataForm.htmlSourceCode; // 如果自定义广告则是富文本编辑器内部编辑的内容
                        let provinceId = this.dataForm.provinceId; // 代理商省ID
                        let cityId = this.dataForm.cityId; // 代理商市ID
                        let areaId = this.dataForm.areaId; // 代理商区ID
                        let imgPic = this.dataForm.imgPic;
                        this.loading = true;
                        updateAdvert(
                            pId,
                            advertName, // 广告名称
                            advertType, // 广告类型
                            remark, // 备注
                            advertAppType, // 指定位置
                            showTime, // 设置显示时间
                            iosPicOne, // ios图片 1242*2208
                            iosPicTWO, // ios图片 640*1136
                            iosPicThree, // ios图片 640*960
                            androidPic, // android图片 720*1280
                            advertOrCustom, // 广告展现形式 0:广告链接 1：自定义
                            linkUrl, // 如果是广告链接则填上链接地址
                            htmlSourceCode, // 如果自定义广告则是富文本编辑器内部编辑的内容
                            provinceId, // 代理商省ID
                            cityId, // 代理商市ID
                            areaId, // 代理商区ID
                            imgPic
                        ).then(response => {
                            this.loading = false;
                            if (response.data.status == 200) {
                                this.$message.success(response.data.errorMsg);
                                this.$router.go(-1);
                                this.$store.dispatch('UpdateCache', true);
                            } else {
                                this.$message.error(response.data.errorMsg);
                            }
                        }).catch(() => {
                            this.loading = false;
                        });
                    }).catch(() => {
                        this.$message({type: 'info', message: '已取消'});          
                    });
                } else {
                    return false;
                }
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.top-title{
    text-align: center;
    font-size: 18px;
    color: #333;
    height: 78px;
    line-height: 78px;
    font-weight: bold;
    border-bottom: 1px solid #ddd;
}
    .app-container {
        position: relative;
        padding: 20px 20px 10px;
       
        .main-container {
            position: relative;
            padding: 20px 30px 10px;
            background: #fff;
            box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
            -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
            .man-bom{
                margin: 20px 0;
                margin-top: 100px;
            }
            .box{
                margin: 20px 0
            }
            .title {
                position: relative;
                font-size: 14px;
                color: rgb(106, 85, 72);
                padding-left: 14px;
                margin: 30px 0;
                display: block;
                text-indent: 16px;
                &::after {
                    position: absolute;
                    content: "";
                    width: 4px;
                    height: 14px;
                    background: #ff5e2c;
                    left: 0;
                    top: 4px;
                }
            }
            .title-pic {
                margin-top: 80px;
            }
            .describe {
                font-size: 14px;
                color: #666;
                margin: 20px 0;
            }
            i {
                font-style: normal;
                color: #999;
            }
            .item {
                padding-left: 30px;
            }
        }
        .item-adv {
            padding-left: 10px;
        }
        // .item-pic {
        //     padding-left: 14px;
        // }
    }
</style>